<template>
  <div class="layout-col plr15 pb15">
    <div class="layout-col bs">
      <div class="ww100 flex-bc plr12 ptb8 bs2">
        <div class="flex-sc">
          <div class="h30"><img class="hh100" src="@/assets/images/tibi-ico.png" /></div>
          <span class="f15 fw ml8">告警日志</span>
        </div>
        <div class="flex-ec cursor flex1">
          <div class="ml15 mr10">设备选择</div>
          <div class="flex w50x4">
            <el-select v-model="state.sensor_id" placeholder="请选择" style="width: 100%" clearable filterable>
              <el-option label="全部" value="" />
              <el-option v-for="(v, i) in state.sensorList" :key="v.id" :label="v.name" :value="v.id" />
            </el-select>
          </div>
          <div class="ml15 mr10">时间范围</div>
          <div class="flex w50x8">
            <el-date-picker v-model="state.datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" />
          </div>
          <el-button class="bgi3 white ml15" @click.stop="state.page = 1; init()" :icon="Search">搜索</el-button>
          <el-button class="bgi3 white" @click.stop="exports()" :icon="Filter">导出</el-button>
          <el-button class="bgi3 white" @click.stop="handleClick('selectAll')" :icon="Operation">全选</el-button>
          <el-button class="bgi3 white" @click.stop="handleClick('deals')" :icon="Edit">批量处理</el-button>
        </div>
      </div>
      <div class="row bgi22">
        <div :style="{textAlign: v.align}" v-for="(v, i) in state.content" :key="i" v-show="v.show" :class="typeof(v.key) == 'object'?v.width +' '+ 'mlr5':v.width">{{v.name}}</div>
      </div>
      <div class="table">
        <div class="row" :class="publicStore.active[state.key] == item[state.key] || item['click']?'active':index%2 == 1?'bgi23':'bgi18'" v-for="(item, index) in state.list" :key="index" @click="handleClick('active', item)">
          <div v-show="v.show" :class="v.width" :style="{textAlign: v.align}" v-for="(v, i) in state.content" :key="i">
            <span v-if="typeof(v.key) == 'object'" class="i21 cursor mlr5" :class="kk=='add'?'none':kk=='deal'&&item['clear_type']!=0?'none':''" v-for="(vv, kk, ii) in v.key" :key="ii" @click.stop="handleClick(kk, item)">{{vv}}</span>
            <span v-else-if="v.key=='*'">{{index+1}}</span>
            <span v-else-if="v.type == 'time'">{{item[v.key] == 0?'/':parseTime(item[v.key])}}</span>
            <span v-else-if="v.type == 'find'" :class="find(v.value[0], [v.value[1], item[v.key]], 'color')?find(v.value[0], [v.value[1], item[v.key]], 'color'):''">
              {{find(v.value[0], [v.value[1], item[v.key]], v.value[2])}}
            </span>
            <span v-else-if="v.type == 'switch'">
              <el-switch v-model="item[v.key]" :active-text="v.value[1].name" :inactive-text="v.value[0].name" :active-value="v.value[1].value" :inactive-value="v.value[0].value" inline-prompt @change="handleClick('switch', item)"></el-switch>
            </span>
            <span v-else-if="v.type == 'input'"><el-input v-model="item[v.value]" placeholder="请输入" style="width: 150px;" size="small" /></span>
            <span v-else>{{isNull(item[v.key]) && v.key!=''? '/' : item[v.key]}}</span>
          </div>
        </div>
        <div v-if="state.empty" class="flex-cc ww100 tc ptb13 bgi18">没有数据</div>
      </div>
      <Pagination class="plr20" v-show="state.total>0" :total="state.total" v-model:page.sync="state.page" v-model:limit.sync="state.limit" @pagination="init" />
      <Deal @init="init" title="告警处理" ref="exposeRef" />
      <Alarm @init="init" title="告警分析" ref="alarmRef" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { Refresh, Search, Filter, Connection, Edit, Operation } from '@element-plus/icons-vue'
  import Pagination from '@/components/Pagination'
  import Deal from '@/components/Deal'
  import Alarm from '@/components/Alarm'
  const route = useRoute()
	const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  const configStore = proxy.configStore()
  let logType = $ref([
    {value: '0', name: '未处理',   color: 'i8'},
    {value: '1', name: '已处理',   color: 'i21'},
    {value: '2', name: '自动消除', color: 'ca'},
  ])
  const state = reactive({
	  ...publicStore.$state,
    key: 'id',
    query: {"o": "o_sensor_alarm_log"},
    content: [
      { width: 'w70',   show: true, align: 'center', key: '*', name: '序号' },
      { width: 'w50x5', show: true, align: 'left',  key: 'sensor_name', name: '设备名称' },
      { width: 'w50x8', show: true, align: 'left',  key: 'sensor_instlPos', name: '安装位置' },
      { width: 'w50x4', show: true, align: 'left',  key: 'alarm_time', name: '告警时间', type: 'time' },
      { width: 'w50x2', show: true, align: 'center',  key: 'activation_count', name: '次数' },
      { width: 'w50x2', show: true, align: 'center', key: 'alarm_description', name: '告警原因' },
      { width: 'w50x2', show: true, align: 'center', key: 'clear_type', name: '处理状态', type: 'find', value: [logType, 'value', 'name'] },
      { width: 'flex1', show: true, align: 'left',  key: 'clear_description', name: '处理方案' },
      { width: 'w50x4', show: true, align: 'left',  key: 'clear_time', name: '处理时间', type: 'time' },
      { width: 'w50x2', show: true, align: 'left',  key: 'clear_by_name', name: '处理人员' },
      { width: 'w50x4', show: true, align: 'right', key: {deal: '处理', view: '查看', viewdata: '分析'},  name: '操作' },
    ],
		sensorList: [],
    sensor_id: '',
    clickArr: [],
  })
  let exposeRef = $ref()
  let alarmRef = $ref()
 
  onMounted(async() => {
    state.form = route.query
    await getInit()
    await init()
  })

  const getInit = async () => {
    let query =  {"o": "o_sensor", "p": [publicStore.distributId], "i": 0}
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    state.sensorList = proxy.isNull(res)? [] : res.filter(a=>a.class == 0 && a.type == state.form.type)
  }

  const init = async () => {
    getQuery()
    state.params = {queryApi: Object.assign({s: (state.page -1)*state.limit, n: state.limit}, state.query), queryApiCount: state.query}
    let res = await publicStore.post(state.params)
    state.list = proxy.isNull(res.queryApi)? [] : res.queryApi
    state.empty = proxy.isNull(res.queryApi)? true : false
    state.total = proxy.isNull(res.queryApiCount)? 0 : parseInt(res.queryApiCount[0].count)
  }

    // 检索条件
  const getQuery  = () => {
    if(state.form.type){
      console.log('类型告警-------')
      if(!state.sensor_id && proxy.isNull(state.datetime)){
        state.query.p = [publicStore.distributId, state.form.type]
        state.query.i = 16
      }
      // 检索设备
      if(state.sensor_id && proxy.isNull(state.datetime)){
        state.query.p = [publicStore.distributId, state.sensor_id]
        state.query.i = 8
      }
      // 检索时间段
      if(!state.sensor_id && !proxy.isNull(state.datetime)){
        let start = Date.parse(state.datetime[0]) + ''
        let end = Date.parse(state.datetime[1]) + ''
        state.query.p = [publicStore.distributId, state.form.type, start, end]
        state.query.i = 17
      }
      // 传感器 + 时间段
      if(state.sensor_id && !proxy.isNull(state.datetime)){
        let start = Date.parse(state.datetime[0]) + ''
        let end = Date.parse(state.datetime[1]) + ''
        state.query.p = [state.sensor_id, start, end]
        state.query.i = 10
      }
    }else{
      console.log('站告警-------')
      if(!state.sensor_id && proxy.isNull(state.datetime)){
        state.query.p = [publicStore.distributId]
        state.query.i = 0
      }
      // 检索传感器
      if(state.sensor_id && proxy.isNull(state.datetime)){
        state.query.p = [publicStore.distributId, state.sensor_id]
        state.query.i = 8
      }
      // 检索时间段
      if(!state.sensor_id && !proxy.isNull(state.datetime)){
        let start = Date.parse(state.datetime[0]) + ''
        let end = Date.parse(state.datetime[1]) + ''
        state.query.p = [publicStore.distributId, start, end]
        state.query.i = 9
      }
      // 传感器 + 时间段
      if(state.sensor_id && !proxy.isNull(state.datetime)){
        let start = Date.parse(state.datetime[0]) + ''
        let end = Date.parse(state.datetime[1]) + ''
        state.query.p = [state.sensor_id, start, end]
        state.query.i = 10
      }
    }
  }

  const handleClick = (remark, val) => {
    if(remark == 'deal'){
      exposeRef.onVisable(val)
    }
    if(remark == 'deals'){
      if (state.clickArr.length == 0) return  ElNotification({ title: '提示', message: '至少选中一条', type: 'error' })
      exposeRef.onVisable(state.clickArr)
    }
    if(remark == 'viewdata'){
      alarmRef.onVisable(val)
    }
    if(remark == 'active'){
      let clickIndex = state.clickArr.findIndex(a=>a[state.key] == val[state.key])
      if(clickIndex != -1){
        val.click = false
        state.clickArr.splice(clickIndex, 1)
      }else{
        if(val.clear_type == '0'){
          val.click = true
          state.clickArr.push(val)
        }
      }
    }
    if(remark == 'selectAll'){
      let clickIndex = state.list.findIndex(a=>{ return a['click'] })
      if(clickIndex == -1){
        state.list.forEach(item => {
          if(item.clear_type == '0') {
            item.click = true
            state.clickArr.push(item)
          }
        })
      }else{
        state.clickArr = []
        state.list.forEach(item => {delete item['click']})
      }
    }
    if(remark == 'view'){
      let query = {id: val.sensor_id, name: val.sensor_name, type: val.sensor_type, instlPos: val.sensor_instlPos, alarm_time: val.alarm_time}
      proxy.toPath('/chart', query)
    }
  }

  const exports = async() => {
    let query = Object.assign({}, state.query)
    delete query.s
    delete query.n
    let params = {queryApi: query}
    let tempData = await publicStore.post(params)
    import('@/utils/Export2Excel').then(async excel => {
      const tHeader   = []
      const filterVal = []
      state.content.forEach(item => {
        if(item.show && item.key != '*' && typeof(item.key) != 'object'){
          tHeader.push(item.name)
          filterVal.push(item.key)
        }
      })
      const data = formatJsons(filterVal, tempData)
      excel.export_json_to_excel({
        header: tHeader,
        data,
        filename: proxy.parseTime(new Date()) + '导出'
      })
    })
  }

  const formatJsons = (filterVal, data) => {
    let list = data? data : state.list
    return list.map(v => filterVal.map(j => {
      if(j=="alarm_time" || j=="clear_time"){
        return v[j]&&v[j]!='0'? proxy.parseTime(v[j]) : ''
      }else if(j=="clear_type"){
        return proxy.find(logType, ['value', v[j]], 'name')
      }else{
        return v[j]
      }
    }))
  }


</script>
  
<style scoped lang="scss">

</style>
  